package com.example.onedemotest.slice;

import com.example.onedemotest.MainAbility;
import com.example.onedemotest.ResourceTable;
import com.example.onedemotest.handle.MyEventHandler;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.dispatcher.Group;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.Revocable;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.event.commonevent.*;
import ohos.event.intentagent.IntentAgent;
import ohos.event.intentagent.IntentAgentConstant;
import ohos.event.intentagent.IntentAgentHelper;
import ohos.event.intentagent.IntentAgentInfo;
import ohos.event.notification.NotificationHelper;
import ohos.event.notification.NotificationRequest;
import ohos.event.notification.NotificationSlot;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.rpc.RemoteException;

import java.util.ArrayList;
import java.util.List;

/**
 * 通知测试
 */
public class CommonEventSlice extends AbilitySlice {

    private HiLogLabel hiLogLabel=new HiLogLabel(HiLog.LOG_APP,0x11,"CommonEventSlice");
    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_slice_commont_event);
        Text norrmalTxt = (Text) findComponentById(ResourceTable.Id_normalTxt);
        norrmalTxt.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {

                NotificationSlot slot1=new NotificationSlot("slot1","一般通知",NotificationSlot.LEVEL_DEFAULT);
                NotificationSlot slot2=new NotificationSlot("slot2","重要通知",NotificationSlot.LEVEL_HIGH);
                //锁屏通知
                slot2.setLockscreenVisibleness(NotificationRequest.VISIBLENESS_TYPE_PUBLIC);
                //允许增东
                slot2.setEnableVibration(true);
                //绕过免打扰模式
                slot2.enableBypassDnd(true);
                NotificationRequest.NotificationNormalContent normalContent=new NotificationRequest.NotificationNormalContent();
                normalContent.setTitle("这是通知").setText("测试通知内容").setAdditionalText("副标题");
                NotificationRequest.NotificationContent notificationContent=new NotificationRequest.NotificationContent(normalContent);
                NotificationRequest notificationRequest=new NotificationRequest(0x11)
                        .setContent(notificationContent)
                        .setSlotId("slot2")
                        .setIntentAgent(CreateIntentAgent());
                try {
                    NotificationHelper.addNotificationSlot(slot1);
                    NotificationHelper.addNotificationSlot(slot2);
                    NotificationHelper.publishNotification(notificationRequest);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });

        sendMyCommonEventService();
        testCommonEventService();
//        testDispatcher();
//        testGroupTask();
        testBarrierTask();
    }

    private IntentAgent CreateIntentAgent(){

        Operation operation= new Intent.OperationBuilder().withDeviceId("")
                .withBundleName(getBundleName())
                .withAbilityName(MainAbility.class.getName())
                .build();

        Intent intent=new Intent();
        intent.setOperation(operation);
        List<Intent>intents=new ArrayList<>();
        intents.add(intent);
        List<IntentAgentConstant.Flags>flags=new ArrayList<>();
        flags.add(IntentAgentConstant.Flags.ONE_TIME_FLAG);
        IntentAgentInfo agentInfo=new IntentAgentInfo(200, IntentAgentConstant.OperationType.START_ABILITY
        ,flags,intents,null
        );
      return  IntentAgentHelper.getIntentAgent(this,agentInfo);
    }

    CommonEventSubscriber subscriber;
    //测试订阅系统公共事件
    private void testCommonEventService(){

        MatchingSkills matchingSkills=new MatchingSkills();
//        matchingSkills.addEvent(CommonEventSupport.COMMON_EVENT_ABILITY_ADDED);
        matchingSkills.addEvent("com.test.myAction");

        CommonEventSubscribeInfo subscribeInfo=new CommonEventSubscribeInfo(matchingSkills);

        subscriber =new CommonEventSubscriber(subscribeInfo) {
            @Override
            public void onReceiveEvent(CommonEventData commonEventData) {
                switch (commonEventData.getIntent().getAction()){
                    case "com.test.myAction":
                        new ToastDialog(CommonEventSlice.this).setText("接收到有序事件"+commonEventData.getCode()).show();
                        break;
                }
            }
        };
        try {
            CommonEventManager.subscribeCommonEvent(subscriber);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    //发送自定义的公共事件
    private void sendMyCommonEventService(){
        Operation operation=new Intent.OperationBuilder().withAction("com.test.myAction").build();
        Intent intent = new Intent();
        intent.setOperation(operation);
        CommonEventData commonEventData=new CommonEventData(intent);
        commonEventData.setData("结果数据");
        commonEventData.setCode(200);

        CommonEventPublishInfo commonEventPublishInfo=new CommonEventPublishInfo();
        //粘性事件
//        commonEventPublishInfo.setSticky(true);
        commonEventPublishInfo.setOrdered(true);
        try {
            CommonEventManager.publishCommonEvent(commonEventData,commonEventPublishInfo);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onStop() {
        super.onStop();
        try {
            CommonEventManager.unsubscribeCommonEvent(subscriber);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    //使用任务分发
    private void testDispatcher(){
        //全局任务分发
        TaskDispatcher taskDispatcher = getGlobalTaskDispatcher(TaskPriority.DEFAULT);

        taskDispatcher.asyncDispatch(new Runnable() {
            @Override
            public void run() {
                HiLog.info(hiLogLabel, "任务1");
            }
        });
        taskDispatcher.syncDispatch(new Runnable() {
            @Override
            public void run() {
                HiLog.info(hiLogLabel, "任务2");
            }
        });
        HiLog.info(hiLogLabel, "任务3");
//        //异步延迟任务分发
//        Revocable revocable = taskDispatcher.delayDispatch(new Runnable() {
//            @Override
//            public void run() {
//                HiLog.info(hiLogLabel, "执行异步方法");
//                try {
//                    Thread.sleep(2000);
//                    HiLog.info(hiLogLabel, "异步方法执行完毕");
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        }, 5000);
//        //可以用来停止分发任务
//        revocable.revoke();
//
//        HiLog.info(hiLogLabel,"方法执行完毕");
    }

    private void testGroupTask(){
        String dispatchName="ParallelPatcher";
        TaskDispatcher parallelTaskDispatcher = createParallelTaskDispatcher(dispatchName, TaskPriority.DEFAULT);
        //创建任务组
        Group group = parallelTaskDispatcher.createDispatchGroup();

        parallelTaskDispatcher.asyncGroupDispatch(group, new Runnable() {
            @Override
            public void run() {
                HiLog.info(hiLogLabel, "任务1");
            }
        });

        //所有任务完成
        parallelTaskDispatcher.groupDispatchNotify(group, new Runnable() {
            @Override
            public void run() {
                HiLog.info(hiLogLabel, "所有任务完成");
            }
        });
        parallelTaskDispatcher.asyncGroupDispatch(group, new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                    HiLog.info(hiLogLabel, "任务2");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    private void testBarrierTask(){
        TaskDispatcher dispatcher = createParallelTaskDispatcher("parallelTask", TaskPriority.DEFAULT);
        Group group = dispatcher.createDispatchGroup();
        dispatcher.asyncGroupDispatch(group, new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                HiLog.info(hiLogLabel, "任务1");
            }
        });

        dispatcher.asyncGroupDispatch(group, new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                HiLog.info(hiLogLabel, "任务2");
            }
        });
        dispatcher.asyncDispatchBarrier(new Runnable() {
            @Override
            public void run() {
                HiLog.info(hiLogLabel, "任务3");
            }
        });
        dispatcher.asyncDispatchBarrier(new Runnable() {
            @Override
            public void run() {
                HiLog.info(hiLogLabel, "任务4完成");
                //b把异步线程的数据发送到主线程更新ui
                initInnerEvent();

            }
        });

        HiLog.info(hiLogLabel, "任务5");
    }

    private void initInnerEvent(){
        //2. 创建 EventRunner，以手动模式为例。
        // create()的参数是 true 时，则为托管模式
        EventRunner runner = EventRunner.create(false);
        if (runner == null) {
            return;
        }
        MyEventHandler myEventHandler = new MyEventHandler(runner);

        int eventId1 = 0;
        int eventId2 = 1;
        long param = 0;
        Object object = null;
        InnerEvent innerEvent = InnerEvent.get(eventId1, param,object);
        InnerEvent innerEvent2 = InnerEvent.get(eventId2, param,object);

        //投递事件
        myEventHandler.sendEvent(innerEvent,0, EventHandler.Priority.IMMEDIATE);
        myEventHandler.sendEvent(innerEvent2,5000, EventHandler.Priority.IMMEDIATE);

        //投递runnable 到任务队列
        myEventHandler.postTask(new Runnable() {
            @Override
            public void run() {
                HiLog.info(hiLogLabel, "task1 running");
            }
        },EventHandler.Priority.IMMEDIATE);

        //6. 启动和停止 EventRunner，如果为托管模式，则不需要此步骤。
        runner.run();


//        runner.stop();
    }
}
